package shorturl.storage;


import shorturl.base.IShorterEntity;
import shorturl.IShorterStorage;
import shorturl.entity.ShorterWithPassword;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 使用Map作为短链接存储器
 * 使用此方式作为存储器不会出现一个原始链接对应多个短链接的情况
 */
public class MapShorterStorage implements IShorterStorage {

    /**
     * 存储原始链接,短链接对象
     */
    Map<String, IShorterEntity> urlMap = new ConcurrentHashMap<>();
    /**
     * 存储短链接字符串,短链接对象
     */
    Map<String, IShorterEntity> shorterStringUrlMap = new ConcurrentHashMap<>();

    @Override
    public String get(String shorterString, String password) {
        IShorterEntity shorter = shorterStringUrlMap.get(shorterString);
        if (shorter != null) {
            if (password != null && shorter instanceof ShorterWithPassword &&
                    Objects.equals(password, ((ShorterWithPassword) shorter).getPassword()) && shorter.verify()) {
                return shorter.getUrl();
            } else if (password == null && shorter.verify()) {
                return shorter.getUrl();
            }
            cleanShorterString(shorterString);
        }
        return null;
    }

    @Override
    public void clean(String url) {
        IShorterEntity shorter = urlMap.get(url);
        if (shorter != null) {
            urlMap.remove(url);
            shorterStringUrlMap.remove(shorter.getShorterString());
        }
    }

    @Override
    public void cleanShorterString(String shortserString) {
        IShorterEntity shorter = shorterStringUrlMap.get(shortserString);
        if (shorter != null) {
            urlMap.remove(shorter.getUrl());
            shorterStringUrlMap.remove(shorter.getShorterString());
        }
    }

    @Override
    public void save(String url, IShorterEntity shorter) {
        if(urlMap.get(url) != null){
            clean(url);
        }
        urlMap.put(url, shorter);
        shorterStringUrlMap.put(shorter.getShorterString(), shorter);
    }

    @Override
    public void clean() {
        shorterStringUrlMap.clear();
        urlMap.clear();
    }

    @Override
    public boolean hasShorterString(String shorterString) {
        return shorterStringUrlMap.get(shorterString) != null;
    }
}
